package org.crmsystem.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.crmsystem.dao.StaffMapper;
import org.crmsystem.dao.UserMapper;
import org.crmsystem.model.Page;
import org.crmsystem.model.Staff;
import org.crmsystem.model.User;
import org.crmsystem.service.IStaffService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * 员工服务层实现
 * @author 孙艳平
 *
 */
@Service
public class StaffServiceImpl implements IStaffService {
	@Autowired
	private StaffMapper staffMapper;
	@Autowired
	private UserMapper userMapper;
	/**
	 * 根据id获取员工详细信息
	 */
	public Staff getStaffById(int id) {
		return staffMapper.getStaffById(id);
	}

	/**
	 * 多条件查询获取员工列表
	 * @param map
	 * @return
	 */
	public Page getStaff(Map map) {
		Staff staff=(Staff) map.get("staff");
		Page page=new Page();
		Map map1=new HashMap();
		map1.put("staff",staff);
		map1.put("startDate",map.get("startDate"));
		map1.put("endDate",map.get("endDate"));
		int totalNum=staffMapper.staffCount(map1);
		page.setTotalNum(totalNum);
		int pageSize=Integer.parseInt(String.valueOf(map.get("pageSize")));
		page.setPageSize(pageSize);
		int currPage=Integer.parseInt(String.valueOf(map.get("currPage")));
		page.setCurrPage(currPage);
		page.setResult(staffMapper.getStaff(map));
		page.setTotalPage(totalNum%pageSize==0?totalNum/pageSize:totalNum/pageSize+1);
		return page;
	}

	/**
	 * 添加员工
	 */
	public int addStaff(Staff staff) {
		return staffMapper.addStaff(staff);
	}
	/**
	 * 删除员工
	 */
	@Transactional
	public int delStaff(int id) {
		User user=new User();
    	user.setStaffId(id);
    	Map map=new HashMap();
    	map.put("user", user);
    	map.put("currPage", 0);
    	map.put("pageSize", 0);
    	List<Object> list=userMapper.getUser(map);
    	for(int i=0;i<list.size();i++){
    		User user1=(User)list.get(i);
    		user1.setStaffId(-1);
    		int flag=userMapper.updateUser(user1);
    	}
        return staffMapper.delStaff(id);
	}

	/**
	 * 更新员工
	 */
	public int updateStaff(Staff staff) {
		return staffMapper.updateStaff(staff);
	}
	/**
	 * 根据员工名称查找员工Id
	 */
	public Integer getIdByName(String name) {
		return staffMapper.getIdByName(name);
	}

}
